package com.qubuyer.business.mine.activity

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.widget.doAfterTextChanged
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.SpanUtils
import com.qubuyer.R
import com.qubuyer.business.mine.view.SelectWithdrawAccountDialog
import com.qubuyer.business.mine.viewmodel.WalletViewModel
import com.qubuyer.core.app.MVVMFragment
import com.qubuyer.databinding.FragmentWithdrawBinding
import com.qubuyer.repository.entitys.UserEntity
import com.qubuyer.utils.EditTextUtils
import com.qubuyer.utils.NavigationUtil
import com.qubuyer.utils.StringUtil
import java.util.*

/**
 * @author Susong
 * @date 创建时间:2019/4/13
 * @description 提现activity
 * & @version
 */
class WithdrawFragment : MVVMFragment<FragmentWithdrawBinding, WalletViewModel>() {
    override fun onDataBinding(dataBinding: FragmentWithdrawBinding) {
        dataBinding.host = this
    }

    override fun getTitle(): String {
        return "提现"
    }

    override val viewModel: WalletViewModel by injectVMByActivity()

    override val layoutId: Int
        get() = R.layout.fragment_withdraw

    private val selectWithdrawAccountDialog: SelectWithdrawAccountDialog by lazy {
        SelectWithdrawAccountDialog(mContext, viewLifecycleOwner, viewModel.userEntity.value) { type ->
            mSelectedWithdrawType = type
            when (type) {
                1 -> {
                    viewDataBinding.ivWithdrawTitle.setDrawableId(mContext, R.drawable.icon_withdraw_wechat)
                    viewDataBinding.tvWithdrawTitle.text = "微信支付"
                }
                2 -> {
                    viewDataBinding.ivWithdrawTitle.setDrawableId(mContext, R.drawable.icon_withdraw_alipay)
                    viewDataBinding.tvWithdrawTitle.text = "支付宝"
                }
            }
        }
    }

    //选择的提现类型 1:微信 2:支付宝
    private var mSelectedWithdrawType = -1

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        EditTextUtils.setPricePoint(viewDataBinding.etWithdrawMoney)
        viewDataBinding.tvServiceCharge.visibility = View.GONE
        viewDataBinding.vLine.visibility = View.GONE
        viewDataBinding.tvRealMoney.visibility = View.GONE
        viewDataBinding.etWithdrawMoney.doAfterTextChanged { calcServiceCharge(it.toString()) }
        viewModel.wallet.observe(viewLifecycleOwner, {
            viewDataBinding.tvBalance.text = "可提现余额¥${
                StringUtil.formatAmount(it.money
                        ?: "0.00", 2)
            }"
        })
        viewModel.userEntity.observe(viewLifecycleOwner, {
            initWithdrawAccountInfo(it)
            selectWithdrawAccountDialog.setEntity(it)
        })
    }

    private fun calcServiceCharge(inputWithdrawMoney: String) {
        if (ObjectUtils.isEmpty(viewModel.userEntity.value)) return
        val serviceCharge = viewModel.userEntity.value?.withdrawal_cash
        if (ObjectUtils.isEmpty(inputWithdrawMoney) || ObjectUtils.isEmpty(serviceCharge)) {
            viewDataBinding.tvServiceCharge.visibility = View.GONE
            viewDataBinding.vLine.visibility = View.GONE
            viewDataBinding.tvRealMoney.visibility = View.GONE
            return
        }
        viewDataBinding.tvServiceCharge.visibility = View.VISIBLE
        viewDataBinding.vLine.visibility = View.VISIBLE
        viewDataBinding.tvRealMoney.visibility = View.VISIBLE
        val serviceChargeFloat = serviceCharge!!.toFloat()
        val withdrawMoney = inputWithdrawMoney.toFloat()
        val serviceChargeCalcFloat = withdrawMoney * (serviceChargeFloat / 100)
        SpanUtils.with(viewDataBinding.tvServiceCharge).append(String.format(Locale.CHINA, "服务费:%.2f元", serviceChargeCalcFloat)).setFontSize(ConvertUtils.dp2px(14f)).setForegroundColor(ContextCompat.getColor(mContext, R.color.common_text_color1))
                .appendSpace(ConvertUtils.dp2px(5f))
                .append(String.format(Locale.CHINA, "(费率:%.2f%%)", serviceChargeFloat)).setFontSize(ConvertUtils.dp2px(14f)).setForegroundColor(Color.parseColor("#999999"))
                .create()
        SpanUtils.with(viewDataBinding.tvRealMoney).append("实际到账:").setFontSize(ConvertUtils.dp2px(14f)).setForegroundColor(ContextCompat.getColor(mContext, R.color.common_text_color1))
                .appendSpace(ConvertUtils.dp2px(2f))
                .append(String.format(Locale.CHINA, "%.0f元", withdrawMoney - serviceChargeCalcFloat)).setFontSize(ConvertUtils.dp2px(14f)).setForegroundColor(Color.parseColor("#FE761C"))
                .create()
    }

    private fun initWithdrawAccountInfo(entity: UserEntity?) {
        if (null != entity) {
            when {
                entity.is_bind_wx == 1 -> {
                    viewDataBinding.llAddAccount.visibility = View.GONE
                    viewDataBinding.rlThridAccount.visibility = View.VISIBLE
                    viewDataBinding.ivWithdrawTitle.setDrawableId(mContext, R.drawable.icon_withdraw_wechat)
                    viewDataBinding.tvWithdrawTitle.text = "微信支付"
                    mSelectedWithdrawType = 1
                }
                entity.is_bind_alipay == 1 -> {
                    viewDataBinding.llAddAccount.visibility = View.GONE
                    viewDataBinding.rlThridAccount.visibility = View.VISIBLE
                    viewDataBinding.ivWithdrawTitle.setDrawableId(mContext, R.drawable.icon_withdraw_alipay)
                    viewDataBinding.tvWithdrawTitle.text = "支付宝"
                    mSelectedWithdrawType = 2
                }
                else -> {
                    viewDataBinding.llAddAccount.visibility = View.VISIBLE
                    viewDataBinding.rlThridAccount.visibility = View.GONE
                    mSelectedWithdrawType = -1
                }
            }
        }
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.ll_add_account -> mContext.swapContentFragment(ThirdAccountFragment())
            R.id.rl_thrid_account -> selectWithdrawAccountDialog.show()
            R.id.tv_all_withdraw ->
                viewModel.wallet.value?.money?.let {
                    if (it.isNotEmpty()) {
                        viewDataBinding.etWithdrawMoney.setText(StringUtil.formatAmount(it, 2))
                        viewDataBinding.etWithdrawMoney.setSelection(viewDataBinding.etWithdrawMoney.text.length)
                    }
                }
            R.id.tv_get_code -> viewModel.getVerificationCode { toast("验证码获取成功") }
            R.id.tv_confirm_withdraw -> {
                if (mSelectedWithdrawType == -1) {
                    toast("请选择提现账户")
                    return
                }
                val withdrawMoney = viewDataBinding.etWithdrawMoney.text.toString()
                if (TextUtils.isEmpty(withdrawMoney)) {
                    toast("请输入提现金额")
                    return
                }
                val code = viewDataBinding.etCode.text.toString()
                if (TextUtils.isEmpty(code)) {
                    toast("请输入手机验证码")
                    return
                }
                viewModel.withdraw(withdrawMoney, if (mSelectedWithdrawType == 1) "wx" else "alipay", code) {
                    mContext.swapContentFragment(WithdrawResultFragment())
                }
            }
        }
    }
}